package com.lagou.zk.zkconfigure;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.lagou.zk.zkconfigure.zkclient.LagouDataListener;
import com.lagou.zk.zkconfigure.zkclient.PoolConf;
import com.lagou.zk.zkconfigure.zkclient.RegisterConf;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ZkconfigureApplication {

    public static DruidDataSource dataSource =null;

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(ZkconfigureApplication.class, args);
        connectHandler();

        Thread.sleep(Integer.MAX_VALUE);
    }

    public static void connectHandler(){
        //1.创建zkclient
        ZkClient zkClient = new ZkClient(RegisterConf.ZKURL);
        // 读取节点内容
        String confstr = zkClient.readData(RegisterConf.ZKNODE);
        //todo 创建连接池
        createConnPool(confstr);
        // 注册监听
        zkClient.subscribeDataChanges(RegisterConf.ZKNODE, new LagouDataListener());


    }

    /**
     * 创建连接池
     */
    public static void createConnPool(String confstr){
        PoolConf poolConf = JSON.parseObject(confstr, PoolConf.class);
        System.out.println(poolConf);
        dataSource = new DruidDataSource();
        dataSource.setUrl(poolConf.getUrl());
        //dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); //这个可以缺省的，会根据url自动识别
        dataSource.setUsername(poolConf.getUsername());
        dataSource.setPassword(poolConf.getPassword());
        //可选项
        if (poolConf.getInitialSize()!=null) {
            dataSource.setInitialSize(poolConf.getInitialSize());
        }
        if (poolConf.getMaxActive()!=null) {
            dataSource.setMaxActive(poolConf.getMaxActive());
        }
        if (poolConf.getMinIdle()!=null) {
            dataSource.setInitialSize(poolConf.getMinIdle());
        }
        if (poolConf.getMaxWait()!=null) {
            dataSource.setMaxWait(poolConf.getMaxWait());
        }
    }


}
